package ig.metrica.ui;

import ig.util.LoadProperties;
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.event.ComponentEvent;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JInternalFrame;
import javax.swing.JPanel;

import org.eclipse.swt.SWT;
import org.eclipse.swt.awt.SWT_AWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class BrowserCanvas extends Canvas {

    private Thread swtThread;
    private Browser swtBrowser;
    boolean refres = false;

    /**
     * Connect this canvas to a SWT shell with a Browser component and starts a
     * background thread to handle SWT events. This method waits until the
     * browser component is ready.
     */
    public void connect() {
        if (this.swtThread == null) {
            final Canvas canvas = this;
            this.swtThread = new Thread() {

                @Override
                public void run() {
                    try {
                        Display display = new Display();
                        Shell shell = SWT_AWT.new_Shell(display, canvas);
                        shell.setLayout(new FillLayout());
                        //System.out.println("---> 1");
                        synchronized (this) {
                            swtBrowser = new Browser(shell, SWT.NONE);
                            this.notifyAll();
                        }
                        //System.out.println("---> 2");
                        shell.open();
                        //getBrowser().setUrl( url );
                        while (!isInterrupted() && !shell.isDisposed()) {
                            if (!display.readAndDispatch()) {
                                display.sleep();
                            }
                            /*try {
                                Thread.sleep(refresTime * 1000);
                            } catch (InterruptedException ex) {
                                ex.printStackTrace();
                            } */                           
                        }
                        //System.out.println("---> 3");
                        shell.dispose();
                        //display.dispose();
                    } catch (Exception e) {
                        interrupt();
                    }
                }
            };
            this.swtThread.start();
        }

        // Wait for the Browser instance to become ready
        synchronized (this.swtThread) {
            while (this.swtBrowser == null) {
                try {
                    this.swtThread.wait(100);
                } catch (InterruptedException e) {
                    this.swtBrowser = null;
                    this.swtThread = null;
                    break;
                }
            }
        }
    }

    /**
     * Returns the Browser instance. Will return "null" before "connect()" or
     * after "disconnect()" has been called.
     */
    public Browser getBrowser() {
        return this.swtBrowser;
    }

    /**
     * Stops the swt background thread.
     */
    public void disconnect() {
        if (swtThread != null) {
            swtBrowser = null;
            swtThread.interrupt();
            swtThread = null;
        }
    }

    /**
     * Ensures that the SWT background thread is stopped if this canvas is
     * removed from it's parent component (e.g. because the frame has been
     * disposed).
     */
    @Override
    public void removeNotify() {
        super.removeNotify();
        disconnect();
    }
    public Integer refresTime = 0;
    public String url = null;
    /**
     * Opens a new JFrame with BrowserCanvas in it
     */
    public static List<JInternalFrame> addUrls(PrincipalMetrica metrica, String _key) {
        // Required for Linux systems
        System.setProperty("sun.awt.xembedserver", "true");
        Properties properties = LoadProperties.loadPropertiess("server/urls.properties");
        Enumeration enumeration = properties.keys();
        List<JInternalFrame> frames = new ArrayList<JInternalFrame>();
        while (enumeration.hasMoreElements()) {
            Object key = enumeration.nextElement();
            if(_key!=null && !key.equals(_key)){
                continue;
            }
            Object object  = properties.get(key);
            Double x = 500.0;
            Double y = 300.0;
            Double xP = 10.0;
            Double yP = 10.0;
            Integer refresTime = null;
            String url = null;
            boolean activo = false;
            if (object.toString().startsWith("[")){
                try {
                    String[] split = object.toString().split("]")[0].replace("[", "").trim().split(",");
                    activo = Boolean.valueOf(split[0].toUpperCase());
                    x = Double.valueOf(split[1]);
                    y = Double.valueOf(split[2]);
                    xP = Double.valueOf(split[3]);
                    yP = Double.valueOf(split[4]);
                    try {refresTime = Integer.valueOf(split[5]);} catch (Exception e) {}
                    url = object.toString().split("]")[1];
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else{
                url = object.toString();
            }
            if(activo){
                BrowserCanvas browserCanvas = new BrowserCanvas();
                browserCanvas.setPreferredSize(new Dimension(800, 600));
                browserCanvas.refresTime=refresTime;
                browserCanvas.url=url;
                JPanel panel = new JPanel(new BorderLayout());
                panel.add(browserCanvas, BorderLayout.CENTER);

                // Add container to Frame
                JInternalFrame internalFrame = new JInternalFrame();
                internalFrame.setVisible(true);

                //internalFrame.setMaximizable(true);
                internalFrame.setClosable(true);
                //internalFrame.setIconifiable(true);
                //internalFrame.setSize(x.intValue(), y.intValue());
                internalFrame.setBounds(xP.intValue(), yP.intValue(), x.intValue(), y.intValue());
                internalFrame.setTitle(key.toString());
                internalFrame.setToolTipText(browserCanvas.url);
                internalFrame.setName(browserCanvas.refresTime+"");
                internalFrame.setContentPane(panel);
                internalFrame.setResizable(true);
                internalFrame.addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
                    public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {}
                    public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
                        JInternalFrame jif = evt.getInternalFrame();
                        ((BrowserCanvas)((JPanel)jif.getContentPane()).getComponent(0)).refres = false;
                        //System.out.println("1");
                    }
                    public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
                        JInternalFrame jif = evt.getInternalFrame();
                        ((BrowserCanvas)((JPanel)jif.getContentPane()).getComponent(0)).refres = false;
                        //System.out.println("2");
                    }
                    public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {}
                    public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {}
                    public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {}
                    public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {}
                });
                internalFrame.addComponentListener(new java.awt.event.ComponentAdapter() {
                    public void componentResized(java.awt.event.ComponentEvent evt) {
                        Properties properties = LoadProperties.loadPropertiess("server/urls.properties");
                        String value = 
                                ((JInternalFrame)evt.getComponent()).getSize().getWidth()+","+
                                ((JInternalFrame)evt.getComponent()).getSize().getHeight()+","+
                                ((JInternalFrame)evt.getComponent()).getX()+","+
                                ((JInternalFrame)evt.getComponent()).getY()+","+
                                ((JInternalFrame)evt.getComponent()).getName();
                        value = "[true,"+value+"]"+ ((JInternalFrame)evt.getComponent()).getToolTipText();                    
                        properties.put(((JInternalFrame)evt.getComponent()).getTitle(), value );
                        LoadProperties.storePropertiess(properties, "server/urls.properties", new Date().toString());
                    }
                    public void componentMoved(ComponentEvent evt) {
                        Properties properties = LoadProperties.loadPropertiess("server/urls.properties");
                        String value = 
                                ((JInternalFrame)evt.getComponent()).getSize().getWidth()+","+
                                ((JInternalFrame)evt.getComponent()).getSize().getHeight()+","+
                                ((JInternalFrame)evt.getComponent()).getX()+","+
                                ((JInternalFrame)evt.getComponent()).getY()+","+
                                ((JInternalFrame)evt.getComponent()).getName();
                        value = "[true,"+value+"]"+ ((JInternalFrame)evt.getComponent()).getToolTipText();
                        properties.put(((JInternalFrame)evt.getComponent()).getTitle(), value );
                        LoadProperties.storePropertiess(properties, "server/urls.properties", new Date().toString());
                    }

                });            
                metrica.setJInternalPanel(internalFrame);
                browserCanvas.connect();
                browserCanvas.getBrowser().getDisplay().asyncExec(new NavegarUrl(browserCanvas, true));
                //browserCanvas.getBrowser().getDisplay().syncExec(new NavegarUrl(browserCanvas, url));
                internalFrame.setSize(internalFrame.getSize().width, internalFrame.getSize().height+1);
                internalFrame.setSize(internalFrame.getSize().width, internalFrame.getSize().height-1);
                frames.add(internalFrame);
            }
        }
        return frames;        
    }

}
    class NavegarUrl implements Runnable{
        private BrowserCanvas browserCanvas=null;
        private boolean refres = false;
        public NavegarUrl(BrowserCanvas browserCanvas, boolean refres) {
            this.browserCanvas=browserCanvas;
            this.refres=refres;
        }

        @Override
        public void run() {
            System.out.println("Get URL : " + browserCanvas.refresTime + " = " + browserCanvas.url);
            browserCanvas.getBrowser().setUrl( browserCanvas.url );
            browserCanvas.refres = browserCanvas.refresTime!=null && browserCanvas.refresTime > 0;
            if( browserCanvas.refres && refres){
                new Refres(browserCanvas).start();
            }
        }
    }

    class Refres extends Thread{
        private BrowserCanvas browserCanvas = null;
        public Refres(BrowserCanvas browserCanvas) {
            this.browserCanvas=browserCanvas;
        }
        
        @Override
        public void run() {
            while( browserCanvas.refres ){
                System.out.println("Get URL, refres: "+browserCanvas.refres +" : " + browserCanvas.url);
                try {Thread.sleep( browserCanvas.refresTime * 1000 );} catch (Exception e) {}
                if( browserCanvas!=null && browserCanvas.refres ){
                    //System.out.println( (browserCanvas!=null) +","+ browserCanvas.refres);
                    browserCanvas.getBrowser().getDisplay().asyncExec(new NavegarUrl(browserCanvas, false));
                }
            }
        }
    }
